import multer from 'multer';
import path from 'path';
import fs from 'fs/promises';
import { config } from '@/config';
import { logger } from './logger';

// 确保上传目录存在
export const ensureUploadDir = async (): Promise<void> => {
  try {
    await fs.access(config.upload.dir);
  } catch {
    await fs.mkdir(config.upload.dir, { recursive: true });
    logger.info(`Created upload directory: ${config.upload.dir}`);
  }
};

// 生成唯一文件名
export const generateUniqueFilename = (originalName: string): string => {
  const timestamp = Date.now();
  const randomString = Math.random().toString(36).substring(2, 15);
  const extension = path.extname(originalName);
  const baseName = path.basename(originalName, extension);
  
  return `${timestamp}-${randomString}-${baseName}${extension}`;
};

// 文件过滤器
const fileFilter = (req: any, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  // 检查文件类型
  if (config.upload.allowedMimeTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error(`File type ${file.mimetype} is not allowed`));
  }
};

/** 本地磁盘存储（回退用） */
const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    try {
      await ensureUploadDir();
      cb(null, config.upload.dir);
    } catch (error) {
      cb(error as Error, '');
    }
  },
  filename: (req, file, cb) => {
    const uniqueName = generateUniqueFilename(file.originalname);
    cb(null, uniqueName);
  }
});

/** 本地磁盘上传 */
export const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: config.upload.maxFileSize,
  },
});

/** 内存上传（用于直传对象存储） */
const memoryStorage = multer.memoryStorage();
export const uploadMemory = multer({
  storage: memoryStorage,
  fileFilter,
  limits: {
    fileSize: config.upload.maxFileSize,
  },
});

// 单文件上传中间件
export const uploadSingle = (fieldName: string) => upload.single(fieldName);

/** 多文件上传到本地 */
export const uploadMultiple = (fieldName: string, maxCount: number = 10) => 
  upload.array(fieldName, maxCount);

/** 单文件内存上传（用于对象存储） */
export const uploadMemorySingle = (fieldName: string) => uploadMemory.single(fieldName);

// 删除文件
export const deleteFile = async (filePath: string): Promise<void> => {
  try {
    await fs.unlink(filePath);
    logger.info(`Deleted file: ${filePath}`);
  } catch (error) {
    logger.error(`Failed to delete file ${filePath}:`, error);
    throw error;
  }
};

// 获取文件信息
export const getFileInfo = async (filePath: string) => {
  try {
    const stats = await fs.stat(filePath);
    return {
      size: stats.size,
      createdAt: stats.birthtime,
      modifiedAt: stats.mtime,
      isFile: stats.isFile(),
      isDirectory: stats.isDirectory(),
    };
  } catch (error) {
    logger.error(`Failed to get file info for ${filePath}:`, error);
    throw error;
  }
};

// 验证文件是否存在
export const fileExists = async (filePath: string): Promise<boolean> => {
  try {
    await fs.access(filePath);
    return true;
  } catch {
    return false;
  }
};

// 创建缩略图（需要sharp库）
export const createThumbnail = async (
  inputPath: string,
  outputPath: string,
  width: number = 200,
  height: number = 200
): Promise<void> => {
  try {
    // 这里需要安装sharp库来处理图片
    // const sharp = require('sharp');
    // await sharp(inputPath)
    //   .resize(width, height, { fit: 'cover' })
    //   .jpeg({ quality: 80 })
    //   .toFile(outputPath);
    
    logger.info(`Thumbnail created: ${outputPath}`);
  } catch (error) {
    logger.error(`Failed to create thumbnail:`, error);
    throw error;
  }
};